#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
    int *add;
    int use_volatile;
} arg_struct;
#ifdef THREAD_SAFE 
volatile 
#endif
int a;
int b;
void *thread_function(void *arg)
{

    arg_struct *args = (arg_struct *)arg;
    if (args->use_volatile)
        a += *(args->add);
    else
        b += *(args->add);
  return arg;
}
int main(int argc, char *argv[])
{
    int use_volatile = 0;
    pthread_t *threads;
    arg_struct arg;
    int i, num_threads;
    for (i = 0; i < argc; i++)
    {
        if (sscanf(argv[i], "%d", &num_threads) == 0)
            continue;
        if (num_threads < 0)
            continue;
        printf("%d threads\n", num_threads);
        use_volatile = 1;
    }
    if (!use_volatile)
    {
        printf("Using default number of threads %d\n", num_threads = 10000);
    }
    arg.add = &num_threads;
    arg.use_volatile = use_volatile;
    threads = (pthread_t *)malloc(num_threads *
                                  sizeof(pthread_t));
    for (i = 0; i < num_threads; i++)
    {
        if (use_volatile)
            pthread_create(&threads[i], NULL, thread_function, &arg);
        else
            pthread_create(&threads[i], NULL, thread_function, &arg);
    }
    for (i = 0; i < num_threads; i++)
        pthread_join(threads[i], NULL);
    printf("a = %d, b = %d\n", a, b);
    free(threads);
    return 0;
}
